package com.siyoumi.app.modules.wechat.service;

import com.alibaba.fastjson.JSONObject;
import com.siyoumi.app.modules.wechat.entity.WechatGroupChatUser;
import com.siyoumi.app.modules.wechat.entity.WechatRoomUser;
import com.siyoumi.app.modules.wechat.entity.WechatNotifyData;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.*;

//看图猜词语
@Slf4j
@Service
public class WeChatEventCai
        implements WechatEvent {
    static public WeChatEventCai getBean() {
        return XSpringContext.getBean(WeChatEventCai.class);
    }

    //词
    public static String getKey(String roomId) {
        return "wechat_room_cai:" + roomId;
    }

    //排行榜
    public static String getKeyRank(String roomId) {
        return "wechat_room_cai:rank|" + roomId;
    }

    @Override
    public XReturn handle(WechatNotifyData data) {
        begin(data);
        cai(data);
        return null;
    }

    public Boolean exists(String roomId) {
        return XRedis.getBean().exists(getKey(roomId));
    }

    /**
     * 抽奖开始
     *
     * @param data
     */
    @SneakyThrows
    public void begin(WechatNotifyData data) {
        if (!data.getIs_at()) {
            return;
        }
        if (!data.getContent().contains("猜词语")) {
            return;
        }

        beginFunc(data);
    }

    public void beginFunc(WechatNotifyData data) {
        WechatOpenApi api = WechatOpenApi.getIns();

        String roomId = data.getRoomid();
        if (exists(roomId)) {
            api.sendTxt(roomId, "猜词语进行中", "");
            return;
        }

        XReturn r = getCaiImg();
        if (r.err()) {
            api.sendTxt(roomId, "服务已停止", "");
        }

        String imgUrl = r.getData("img_url");
        if (!XStr.startsWith(imgUrl, "http")) {
            imgUrl = "https://" + imgUrl;
        }
        //XFile.save();
        //BufferedImage imageBuffer = XFile.toImgBuffer(imgUrl);
        api.sendImage(data.getRoomid(), imgUrl);

        XRedis.getBean().setEx(getKey(roomId), XJson.toJSONString(r), 60 * 60);
    }


    /**
     * 监控答案，是否猜对
     *
     * @param data
     */
    public void cai(WechatNotifyData data) {
        if (XStr.isNullOrEmpty(data.getContent())) {
            return;
        }

        if (!exists(data.getRoomid())) {
            //没有开始
            return;
        }

        String returnStr = XRedis.getBean().get(getKey(data.getRoomid()));
        XReturn r = XReturn.parse(returnStr);
        String name = r.getData("name");
        if (!XStr.contains(data.getContent(), name)) {
            return;
        }
        //答对，立刻删除题目
        XRedis.getBean().del(getKey(data.getRoomid()));

        WechatOpenApi api = WechatOpenApi.getIns();

        List<WechatGroupChatUser> listUser = api.groupchatUser(data.getRoomid());
        //获取群用户名称
        WechatGroupChatUser winUser = listUser.stream().filter(v ->
                v.getId().equals(data.getSender())).findFirst().orElse(null);
        String winUserName = "";
        if (winUser != null) {
            winUserName = winUser.getName();
        }

        //答对了
        String txt = "恭喜 {0} 答对![强][强][强] \n\n"
                + "【答案】{1}\n"
                + "【解释】{2}\n"
                + "【出处】{3}";
        String sendText = XStr.format(txt
                , winUserName
                , r.getData("name")
                , r.getData("meaning")
                , r.getData("source")
        );
        api.sendTxt(data.getRoomid(), sendText, "");

        //发送排行榜
        RMap<String, String> list = XRedis.getBean().getList(getKeyRank(data.getRoomid()));
        String sum = list.get(data.getSender());
        Integer sumInt = XStr.toInt(sum, 0);
        sumInt++;
        list.put(data.getSender(), sumInt.toString());

        List<WechatRoomUser> listRoomUser = new ArrayList<>();
        for (Map.Entry<String, String> entry : list.entrySet()) {
            //获取群用户名称
            WechatGroupChatUser chatUser = listUser.stream().filter(v ->
                    v.getId().equals(entry.getKey())).findFirst().orElse(null);

            WechatRoomUser roomUser = new WechatRoomUser();
            XBean.copyProperties(chatUser, roomUser);
            roomUser.setCount(XStr.toInt(entry.getValue()));

            listRoomUser.add(roomUser);
        }
        Collections.sort(listRoomUser, (u1, u2) -> Integer.compare(u2.getCount(), u1.getCount()));

        StringBuilder sb = new StringBuilder();
        sb.append("【猜词语最新排名】\n");
        for (WechatRoomUser roomUser : listRoomUser) {
            sb.append("\n" + roomUser.getName() + ": " + roomUser.getCount() + "分");
        }

        WechatOpenApi.getIns(null).sendTxt(data.getRoomid(), sb.toString(), "");
    }


    public XReturn getCaiImg() {
        String url = "https://api.whwsh.cn/?s=App.Ldiom.Advanced";

        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.get(url, null);
        XReturn r = XReturn.parse(returnStr);
        Integer ret = r.getData("ret");
        String msg = r.getData("msg");
        r.setErrCode(ret);
        r.setErrMsg(msg);
        if (r.getErrCode() == 200) {
            r.setErrCode(0);
        }

        if (r.ok()) {
            JSONObject data = r.getData("data");
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                r.setData(entry.getKey(), entry.getValue());
            }
        }

        return r;
    }
}
